package com.piper.long_connection.pb_server;

import com.piper.long_connection.pb_model.core.codc.RequestDecoder;
import com.piper.long_connection.pb_model.core.codc.ResponseEncoder;
import com.piper.long_connection.pb_server.handler.OrderHandlerImpl;
import com.piper.long_connection.pb_server.scanner.Invoker;
import com.piper.long_connection.pb_server.scanner.InvokerHoler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.lang.reflect.Method;

/**
 * netty服务端入门
 */
public class Server {

    public static void main(String[] args) {
        initInvoker();
        start();
    }

    /**
     * 启动
     */
    public static void start() {
        // 服务类
        ServerBootstrap b = new ServerBootstrap();

        // 创建boss和worker
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 设置循环线程组事例
            b.group(bossGroup, workerGroup);

            // 设置channel工厂
            b.channel(NioServerSocketChannel.class);

            // 设置管道
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new RequestDecoder());
                    ch.pipeline().addLast(new ResponseEncoder());
                    ch.pipeline().addLast(new ServerHandler());
                }
            });

            b.option(ChannelOption.SO_BACKLOG, 2048);// 链接缓冲池队列大小

            // 绑定端口
            ChannelFuture future = b.bind(10102);
            System.out.println("start!!!");
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void initInvoker() {
        Object orderHandler = new OrderHandlerImpl();
        Method[] methods = orderHandler.getClass().getMethods();
        InvokerHoler.addInvoker((short) 1, (short) 1, Invoker.valueOf(methods[0], orderHandler));
        System.out.println("invoker:" + InvokerHoler.getInvoker((short) 1, (short) 1));
    }

}
